package com.bookmanger.server.service.impl;

import com.bookmanger.common.result.Result;
import com.bookmanger.pojo.Entity.Book;
import com.bookmanger.pojo.Entity.ISBN;
import com.bookmanger.pojo.Entity.PreBook;
import com.bookmanger.pojo.Entity.Reader;
import com.bookmanger.pojo.VO.PrebookVO;
import com.bookmanger.server.mapper.PreBookMapper;
import com.bookmanger.server.service.BorrowService;
import com.bookmanger.server.service.EmailService;
import com.bookmanger.server.service.PreBookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Service
@Slf4j
public class PreBookServiceImpl implements PreBookService {
    
    @Autowired
    private PreBookMapper preBookMapper;
    
    @Autowired
    private EmailService emailService;
    
    // TODO
     @Autowired
     private BorrowService borrowService;
    
    @Override
    public Result processPreBook(int bookId) {
        try {
            // 1. 用bookId在book表中取出对应的isbn_id
            Book book = preBookMapper.getBookById(bookId);
            if (book == null) {
                return Result.error("未找到ID为 " + bookId + " 的图书");
            }
            
            // 2. 在prebook表里面按prebook_time排序，取最早预定isbn_id的读者 (前提是他的status=0)
            PreBook earliestPreBook = preBookMapper.getEarliestPreBookByIsbnId(book.getIsbnId());
            if (earliestPreBook == null) {
                // 如果没有预定用户，将book表里的is_delete置为0，并且对应的isbn_tb表的stock+1
                preBookMapper.updateBookIsPassToZero(bookId);
                preBookMapper.increaseIsbnStock(book.getIsbnId(), 1);
                log.info("图书ID {} 没有预定用户，已将is_delete置为0且库存增加1", bookId);
                return Result.success("没有找到预定该图书的记录，已更新图书状态和库存");
            }
            
            // 3. 获取读者信息
            Reader reader = preBookMapper.getReaderById(earliestPreBook.getReaderId());
            if (reader == null) {
                return Result.error("未找到ID为 " + earliestPreBook.getReaderId() + " 的读者");
            }
            
            // 4. 获取ISBN信息
            ISBN isbnInfo = preBookMapper.getIsbnById(book.getIsbnId());
            if (isbnInfo == null) {
                return Result.error("未找到ISBN信息");
            }
            
            // 5. 通知读者：系统通过读者预留的联系方式发送取书通知，并将inform_time设置为此时的第二天的下午10点
            LocalDateTime informTime = LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.of(22, 0));
            preBookMapper.updateInformTimeAndBookIdById(informTime, bookId, earliestPreBook.getId());
            
            // 发送邮件通知
            String subject = "图书预定通知";
            String content = "您预定的图书《" + isbnInfo.getTitle() + "》已经到达，请于明天下午10点前到图书馆取书。";
            emailService.sendEmail(reader.getEmail(), subject, content);
            
            log.info("已通知读者 {} 预定的图书《{}》已到达", reader.getName(), isbnInfo.getTitle());
            
            return Result.success("预定处理成功");
        } catch (Exception e) {
            log.error("处理预定图书时发生错误", e);
            return Result.error("处理预定图书时发生错误: " + e.getMessage());
        }
    }
    
    @Override
    public Result handleOverduePreBooks() {
        try {
            // 获取所有超时的预定记录（每日的下午10点查一遍prebook表）
            LocalDateTime now = LocalDateTime.now();
            List<PreBook> overduePreBooks = preBookMapper.getOverduePreBooks(now);
            
            for (PreBook preBook : overduePreBooks) {
                // 取消其预定即将status置为1
                preBookMapper.markAsCancelled(preBook.getId());
                
                // 获取图书和读者信息
                Book book = preBookMapper.getBookById(preBook.getBorrowedBookId());
                Reader reader = preBookMapper.getReaderById(preBook.getReaderId());
                
                if (book != null && reader != null) {
                    // 获取ISBN信息
                    ISBN isbnInfo = preBookMapper.getIsbnById(book.getIsbnId());
                    
                    // 发送超时通知邮件
                    String subject = "预定图书超时通知";
                    String content = "您预定的图书《" + (isbnInfo != null ? isbnInfo.getTitle() : "未知图书") + "》由于超时未取，预定已取消。";
                    emailService.sendEmail(reader.getEmail(), subject, content);
                }
                
                // 通知下一位预定者 (即再次运行此方法）
                if (book != null) {
                    processPreBook(book.getId());
                }
            }
            
            return Result.success("超时预定处理完成");
        } catch (Exception e) {
            log.error("处理超时预定记录时发生错误", e);
            return Result.error("处理超时预定记录时发生错误: " + e.getMessage());
        }
    }
    
    @Override
    public Result completePreBookBorrow(int preId, int managerId) {
        try {
            // 根据preId查prebook.Id将prebook表里的相应记录的is_borrowed置为1
            PreBook preBook = preBookMapper.getPreBookById(preId);
            if (preBook == null) {
                return Result.error("未找到ID为 " + preId + " 的预定记录");
            }
            
            // 将此记录中的is_borrowed置为1
            preBookMapper.markAsBorrowed(preId);
            
            // 然后将此记录中的传给借书接口
             int readerId = preBook.getReaderId();
             int bookId = preBook.getBorrowedBookId();
             LocalDateTime informTime = preBook.getInformTime();
             int borrowTableId = borrowService.borrowBook(readerId, bookId, informTime);
            
            // 根据这个borrowTableId将borrow表中的borrow_manager_id置为managerId
            preBookMapper.updateBorrowManagerId(borrowTableId, managerId);
            
            return Result.success("预定借阅完成");
        } catch (Exception e) {
            log.error("完成预定借阅时发生错误", e);
            return Result.error("完成预定借阅时发生错误: " + e.getMessage());
        }
    }

    @Override
    public boolean processPreBook(Integer bookId) {
        Result result = processPreBook(bookId.intValue());
        return result.getCode() == 200;
    }
    
    @Override
    public Result getUnborrowedPreBooks(Integer page, Integer pageSize) {
        try {
            // 设置分页参数
            PageHelper.startPage(page, pageSize);
            List<PrebookVO> preBooks = preBookMapper.getUnborrowedPreBooks();
            PageInfo<PrebookVO> pageInfo = new PageInfo<>(preBooks);
            return Result.success(pageInfo);
        } catch (Exception e) {
            log.error("获取未借阅的预定记录时发生错误", e);
            return Result.error("获取未借阅的预定记录时发生错误: " + e.getMessage());
        }
    }
    
    @Override
    public Result getBorrowedPreBooks(Integer page, Integer pageSize) {
        try {
            // 设置分页参数
            PageHelper.startPage(page, pageSize);
            List<PrebookVO> preBooks = preBookMapper.getBorrowedPreBooks();
            PageInfo<PrebookVO> pageInfo = new PageInfo<>(preBooks);
            return Result.success(pageInfo);
        } catch (Exception e) {
            log.error("获取已借阅的预定记录时发生错误", e);
            return Result.error("获取已借阅的预定记录时发生错误: " + e.getMessage());
        }
    }
    
    @Override
    public Result getPreBooksByReaderKeyword(String keyword, Integer page, Integer pageSize) {
        try {
            // 设置分页参数
            PageHelper.startPage(page, pageSize);
            
            // 根据关键词查询读者ID
            List<Integer> readerIds = preBookMapper.getReaderIdsByKeyword(keyword);
            
            if (readerIds.isEmpty()) {
                PageInfo<PrebookVO> emptyPageInfo = new PageInfo<>(List.of());
                return Result.success(emptyPageInfo);
            }
            
            // 根据读者ID列表查询相关的预定记录
            List<PrebookVO> preBooks = preBookMapper.getPreBooksByReaderIds(readerIds);
            PageInfo<PrebookVO> pageInfo = new PageInfo<>(preBooks);
            return Result.success(pageInfo);
        } catch (Exception e) {
            log.error("根据读者关键词查询预定记录时发生错误", e);
            return Result.error("根据读者关键词查询预定记录时发生错误: " + e.getMessage());
        }
    }
}